package chances.epg.user.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.type.TypeReference;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.commons.utils.DateUtils;
import chances.epg.commons.utils.JSONUtils;
import chances.epg.commons.utils.RequestUtils;
import chances.epg.data.PageBean;
import chances.epg.entity.user.UserCollection;
import chances.epg.user.service.CollectionService;

@RestController
@RequestMapping(value = "/fav/vod")
public class VodCollectionController extends UserAbstractController {
	private static Logger logger = EpgLogFactory.getSystemLogger();

	@Autowired
	private CollectionService collectionService;

	@RequestMapping(value = "/add")
	public UserResultResponse<UserCollection> addCollection(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		logger.debug(request.getRequestURI());
		UserResultResponse<UserCollection> result = new UserResultResponse<UserCollection>();
		result.setStatus(SUCCESS);
		UserCollection collection = this.createUserCollection(request);

		if (StringUtils.isBlank(collection.getUserId()) || StringUtils.isBlank(collection.getContentId())) {
			result.setStatus(VALID_PARAM);
		} else {

			try {
				this.collectionService.addCollection(collection);
			} catch (Throwable ex) {
				result.setStatus(DB_ERROR);
				logger.error("add user history error.", ex);
			}
		}
		return result;
	}

	@RequestMapping(value = "/remove")
	public UserResultResponse<String> removeCollection(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = RequestUtils.getParameter(request, "userId", "");
		String contentId = RequestUtils.getParameter(request, "contentId", "");
		UserResultResponse<String> result = new UserResultResponse<String>();
		result.setResult(contentId);
		result.setStatus(SUCCESS);
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(contentId)) {
			result.setStatus(VALID_PARAM);
		} else {
			try {
				this.collectionService.removeCollection(userId, contentId);
			} catch (Throwable ex) {
				result.setStatus(DB_ERROR);
				logger.error("remove user history error.", ex);
			}
		}
		return result;
	}

	@RequestMapping(value = "/removeCollections")
	public UserResultResponse<String> removeCollections(@RequestBody String body, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		UserResultResponse<String> result = new UserResultResponse<String>();
		result.setStatus(SUCCESS);

		try {
			List<UserCollection> userComments = JSONUtils.toObject(body, new TypeReference<List<UserCollection>>() {
			});
			for (UserCollection userCollection : userComments) {
				if (StringUtils.isNotBlank(userCollection.getUserId())
						&& StringUtils.isNotBlank(userCollection.getContentId()))
					this.collectionService.removeCollection(userCollection.getUserId(), userCollection.getContentId());
			}

		} catch (Throwable ex) {
			result.setStatus(DB_ERROR);
			logger.error("remove user collections error.", ex);
		}
		return result;
	}

	@RequestMapping(value = "/clear")
	public UserResultResponse<String> clearCollection(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = RequestUtils.getParameter(request, "userId", "");
		String category = RequestUtils.getParameter(request, "category", "");
		UserResultResponse<String> result = new UserResultResponse<String>();
		result.setStatus(SUCCESS);

		if (StringUtils.isBlank(userId)) {
			result.setStatus(VALID_PARAM);
		} else {
			try {
				this.collectionService.clearCollections(userId, category);
			} catch (Throwable ex) {
				result.setStatus(DB_ERROR);

				logger.error("clear user history error.", ex);
			}
		}
		return result;
	}

	@RequestMapping(value = "/list")
	public UserResultSetResponse<UserCollection> listCollections(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = RequestUtils.getParameter(request, "userId", "");
		String contentType = RequestUtils.getParameter(request, "contentType", "");
		String category = RequestUtils.getParameter(request, "category", "");
		UserResultSetResponse<UserCollection> result = new UserResultSetResponse<UserCollection>();
		result.setStatus(SUCCESS);
		if (StringUtils.isBlank(userId)) {
			result.setStatus(VALID_PARAM);
		} else {
			PageBean page = this.getPageBean(request);
			Date beginTime = null;
			String strBeginTime = request.getParameter("beginTime");
			if (StringUtils.isNotBlank(strBeginTime)) {
				beginTime = DateUtils.toDateTime(strBeginTime);
			}

			Date endTime = null;
			String strEndTime = request.getParameter("endTime");
			if (StringUtils.isNotBlank(strEndTime)) {
				endTime = DateUtils.toDateTime(strEndTime);
			}

			try {
				List<UserCollection> collectionList = collectionService.listCollections(userId, contentType, category,
						beginTime, endTime, page);
				result.setResultSet(collectionList);
				result.setPageBean(page);
			} catch (Throwable ex) {
				result.setStatus(DB_ERROR);
				logger.error("list user history error.", ex);
			}
		}

		return result;
	}

	@RequestMapping(value = "/query")
	public UserResultSetResponse<UserCollection> queryCollection(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = RequestUtils.getParameter(request, "userId", "");
		String contentId = RequestUtils.getParameter(request, "contentId", "");
		UserResultSetResponse<UserCollection> result = new UserResultSetResponse<UserCollection>();
		result.setStatus(SUCCESS);
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(contentId)) {
			result.setStatus(VALID_PARAM);

		} else {
			try {
				List<UserCollection> collectionList = collectionService.listCollections(userId, contentId);
				result.setResultSet(collectionList);
				result.setPageBean(new PageBean());
			} catch (Throwable ex) {
				result.setStatus(DB_ERROR);

				logger.error("query user history error.", ex);
			}
		}

		return result;
	}
	
	@RequestMapping(value = "/batchDel")
	public UserResultResponse<String> batchDelUserCollection(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String codesStr = RequestUtils.getParameter(request, "codes", "");
		String userId = RequestUtils.getParameter(request, "userId", "");
		UserResultResponse<String> result = new UserResultResponse<String>();
		result.setStatus(SUCCESS);
		if (StringUtils.isEmpty(codesStr)) {
			result.setStatus(SYS_ERROR);
			return result;
		}
		String[] codes = codesStr.split(",");
		try {
			this.collectionService.batchDelUserCollection(codes,userId);
		} catch (Throwable ex) {
			result.setStatus(DB_ERROR);
			logger.error("remove user collections error.", ex);
		}
		return result;

	}

	private UserCollection createUserCollection(HttpServletRequest request) {
		UserCollection collection = new UserCollection();
		collection.setContentId(RequestUtils.getParameter(request, "contentId", ""));
		collection.setContentName(RequestUtils.getParameter(request, "contentName", ""));
		collection.setContentPoster(RequestUtils.getParameter(request, "contentPoster", ""));
		collection.setContentType(RequestUtils.getParameter(request, "contentType", ""));
		collection.setPath(RequestUtils.getParameter(request, "path", ""));
		collection.setUserId(RequestUtils.getParameter(request, "userId", ""));
		collection.setCategory(RequestUtils.getParameter(request, "category", ""));
		return collection;
	}
}
